﻿using System.ComponentModel;
using Microsoft.Xna.Framework;

namespace Xnatlas
{
    public class AtlasedTexture
    {
        public AtlasedTexture(string file, ITextureWrapper textureWrapper)
        {
            FileName = file;
            OriginalTexture = textureWrapper;

            if (OriginalTexture != null)
            {
                Width = OriginalTexture.Width;
                Height = OriginalTexture.Height;
            }
        }

        public string FileName { get; set; }
        public Rectangle AtlasAreaRectangle { get; set; }
        public Vector2 UvCoordinateTopLeft { get; set; }
        public Vector2 UvCoordinateBottomRight { get; set; }
        public int Width { get; private set; }
        public int Height { get; private set; }

        public ITextureWrapper OriginalTexture { get; set; }

        public override string ToString()
        {
            return string.Format("{0} {1}", FileName, AtlasAreaRectangle);
        }

        public Vector2 ConvertRawUvToAtlasUv(Vector2 uv)
        {
            return UvCoordinateTopLeft + (UvCoordinateBottomRight - UvCoordinateTopLeft) * uv;
        }

        public AtlasedTexture FlipVertical()
        {
            float temp = UvCoordinateBottomRight.Y;
            UvCoordinateBottomRight = new Vector2(UvCoordinateBottomRight.X, UvCoordinateTopLeft.Y);
            UvCoordinateTopLeft = new Vector2(UvCoordinateTopLeft.X, temp);
            return this;
        }

        public AtlasedTexture FlipHorizontal()
        {
            float temp = UvCoordinateBottomRight.X;
            UvCoordinateBottomRight = new Vector2(UvCoordinateTopLeft.X, UvCoordinateBottomRight.Y);
            UvCoordinateTopLeft = new Vector2(temp, UvCoordinateTopLeft.Y);
            return this;
        }

        public AtlasedTexture Clone()
        {
            return new AtlasedTexture(FileName + " (clone)", OriginalTexture)
            {
                AtlasAreaRectangle = AtlasAreaRectangle,
                UvCoordinateBottomRight = UvCoordinateBottomRight,
                UvCoordinateTopLeft = UvCoordinateTopLeft
            };
        }
    }
}